<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.7.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="现在的Android项目普遍使用Retrofit+RxJava的组合实现网络接口请求与数据的展现。这一功能通过Kotlin语言的协程功能也可以很方便的实现。">
<meta name="keywords" content="android">
<meta property="og:type" content="article">
<meta property="og:title" content="Android中使用Kotlin协程代替RxJava封装网络请求">
<meta property="og:url" content="https://ricky9090.github.io/2019/06/10/20190610_01/index.html">
<meta property="og:site_name" content="Ricky&#39;s Blog">
<meta property="og:description" content="现在的Android项目普遍使用Retrofit+RxJava的组合实现网络接口请求与数据的展现。这一功能通过Kotlin语言的协程功能也可以很方便的实现。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-10-18T07:54:02.612Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android中使用Kotlin协程代替RxJava封装网络请求">
<meta name="twitter:description" content="现在的Android项目普遍使用Retrofit+RxJava的组合实现网络接口请求与数据的展现。这一功能通过Kotlin语言的协程功能也可以很方便的实现。">
  <link rel="canonical" href="https://ricky9090.github.io/2019/06/10/20190610_01/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>Android中使用Kotlin协程代替RxJava封装网络请求 | Ricky's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ricky's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">A long way to go.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://ricky9090.github.io/2019/06/10/20190610_01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ricky">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ricky's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">Android中使用Kotlin协程代替RxJava封装网络请求

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-06-10 15:26:09" itemprop="dateCreated datePublished" datetime="2019-06-10T15:26:09+08:00">2019-06-10</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-18 15:54:02" itemprop="dateModified" datetime="2019-10-18T15:54:02+08:00">2019-10-18</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>现在的Android项目普遍使用Retrofit+RxJava的组合实现网络接口请求与数据的展现。这一功能通过Kotlin语言的协程功能也可以很方便的实现。</p>
<a id="more"></a>
<p>相比较而言，RxJava功能过于强大，如果仅用于封装网络请求，有些杀鸡用牛刀的感觉。使用Kotlin的协程实现这个需求代码更精简，逻辑也更清晰一些。</p>
<p>以下是一个完整的例子。使用Retrofit结合Kotlin协程，实现网络请求。<br>点击Activity中的按钮，请求V2ex网站的openAPI，成功后在界面中显示结果字段。</p>
<p>Activity中的代码如下：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> : <span class="type">AppCompatActivity</span></span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> loadDataJob: Job? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line">        setContentView(R.layout.activity_main)</span><br><span class="line"></span><br><span class="line">        test_button.setOnClickListener &#123;</span><br><span class="line">            showResult(<span class="string">""</span>)</span><br><span class="line">            loadDataJob?.cancel()  <span class="comment">// 取消之前的加载任务</span></span><br><span class="line">            loadDataJob = loadData(<span class="string">"Livid"</span>)  <span class="comment">// “http://www.v2ex.com/api/members/show.json?username=Livid”</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onDestroy</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onDestroy()</span><br><span class="line">        loadDataJob?.cancel()  <span class="comment">// 取消加载任务</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">showResult</span><span class="params">(resStr: <span class="type">String</span>)</span></span> &#123;</span><br><span class="line">        test_result.text = resStr</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">loadData</span><span class="params">(username: <span class="type">String</span>)</span></span>: Job &#123;</span><br><span class="line">        <span class="keyword">return</span> executeRequest&lt;UserInfo&gt;(</span><br><span class="line">            <span class="comment">//  请求调用</span></span><br><span class="line">            request = &#123;</span><br><span class="line">                userApiManager.getUserInfo(username)</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="comment">//  成功回调</span></span><br><span class="line">            onSuccess = &#123;</span><br><span class="line">                showResult(it.bio)</span><br><span class="line">            &#125;,</span><br><span class="line">            <span class="comment">//  失败回调</span></span><br><span class="line">            onFail = &#123;</span><br><span class="line">                it.printStackTrace()</span><br><span class="line">            &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在<code>loadData</code>函数中，通过<code>execeteRequest</code>方法返回Job对象，<code>executeRequest</code>通过lambda参数分别指定了网络请求，成功与失败时的逻辑操作。</p>
<p><code>UserApiManager</code>类中实现了Retrofit调用的简单封装：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Nullable</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> UserInfo <span class="title">getUserInfo</span><span class="params">(String name)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 类初始化时创建Retrofit以及接口api的实例</span></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    okHttpClient = new OkHttpClient.Builder()</span></span><br><span class="line"><span class="comment">                .connectTimeout(5000, TimeUnit.MILLISECONDS)</span></span><br><span class="line"><span class="comment">                .readTimeout(5000, TimeUnit.MILLISECONDS)</span></span><br><span class="line"><span class="comment">                .retryOnConnectionFailure(true).build();</span></span><br><span class="line"><span class="comment">    retrofitBuilder =</span></span><br><span class="line"><span class="comment">        new Retrofit.Builder().baseUrl("http://www.v2ex.com")</span></span><br><span class="line"><span class="comment">                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())</span></span><br><span class="line"><span class="comment">                .addConverterFactory(GsonConverterFactory.create())</span></span><br><span class="line"><span class="comment">                .client(okHttpClient);</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    retrofit = retrofitBuilder.build();</span></span><br><span class="line"><span class="comment">    mApiService = retrofit.create(UserApiService.class);</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">        </span><br><span class="line">    Response&lt;UserInfo&gt; result = mApiService.getUserInfo(name).execute();  <span class="comment">// 同步请求</span></span><br><span class="line">    <span class="keyword">if</span> (result.isSuccessful()) &#123;</span><br><span class="line">        <span class="keyword">return</span> result.body();</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (result.code() == <span class="number">404</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> Exception(<span class="string">"404 Not Found"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>由于我们要通过协程实现异步加载，因此在网络请求中，使用了<code>execute</code>同步方法。</p>
<p>在点击按钮时，先取消前一次加载请求，再发起新请求；同时在Activity的<code>onDestroy</code>生命周期中，也进行了取消加载请求的处理。</p>
<p><code>executeRequest</code>利用Kotlin协程实现了网络请求封装：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> <span class="title">executeRequest</span><span class="params">(request: <span class="type">suspend</span> ()</span></span> -&gt; T?, onSuccess: (T) -&gt; <span class="built_in">Unit</span> = &#123;&#125;, onFail: (Throwable) -&gt; <span class="built_in">Unit</span> = &#123;&#125;): Job &#123;</span><br><span class="line">    <span class="keyword">val</span> uiScope = CoroutineScope(Dispatchers.Main)  <span class="comment">// UI主线程的CoroutineScope</span></span><br><span class="line">    <span class="keyword">return</span> uiScope.launch &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">val</span> res: T? = withContext(Dispatchers.IO) &#123; request() &#125;  <span class="comment">// IO线程中执行网络请求，成功后返回这里继续执行</span></span><br><span class="line">            res?.let &#123;</span><br><span class="line">                onSuccess(it)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e: CancellationException) &#123;</span><br><span class="line">            Log.e(<span class="string">"executeRequest"</span>, <span class="string">"job cancelled"</span>)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e: Exception) &#123;</span><br><span class="line">            Log.e(<span class="string">"executeRequest"</span>, <span class="string">"request caused exception"</span>)</span><br><span class="line">            onFail(e)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>首先在UI线程中启动协程，当执行到<code>withContext</code>后，<code>request</code>代码块将切换到调度器分配的IO线程上执行，同时<code>executeRequest</code>函数让出控制权，因此UI线程不会阻塞。当<code>request</code>请求完成后，结果赋值给 <strong>res</strong> 变量，UI线程再次回到<code>executeRequest</code>中，继续执行后续部分。</p>
<p>多次点击界面按钮，将打印</p>
<blockquote>
<p>job cancelled</p>
</blockquote>
<p>更改一个错误的url地址，将看到</p>
<blockquote>
<p>request caused exception</p>
</blockquote>
<p>通过协程，在顺序执行的函数中，实现了回调函数的效果，代码逻辑更清晰了。在调用时相对RxJava也更加简洁。</p>
<p><strong>参考文章</strong><br><a href="https://proandroiddev.com/android-coroutine-recipes-33467a4302e9" target="_blank" rel="noopener">Android Coroutine Recipes</a></p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/android/" rel="tag"># android</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2018/05/22/20180522_01/" rel="next" title="使用Node.js+Express搭建App开发调试Server">
                  <i class="fa fa-chevron-left"></i> 使用Node.js+Express搭建App开发调试Server
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/11/15/20191115_01/" rel="prev" title="Kotlin常用内置函数">
                  Kotlin常用内置函数 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Ricky</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/ricky9090" title="GitHub &rarr; https://github.com/ricky9090" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ricky</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.7.1</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

</body>
</html>
